<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Basics;

use App\Logic\Amazon\AdsApi\Authorize;
use App\Models\Basics\AmazonAccountAds;
use Illuminate\Http\JsonResponse;

class AmazonAccountAdsAjax {

    /**
     * 授权账号
     * @param $id
     * @return JsonResponse
     */
    public function doOauth($id): JsonResponse
    {
        try{
            $model = AmazonAccountAds::query()->findOrFail($id);
            if($model->amazon_account->status != 1){
                return response()->json(['status' => false, 'message' => '账号状态异常！']);
            }
            if($model->auth_status == 1 && $model->refresh_token && $model->auth_at){
                $authAtExpired = strtotime($model->auth_at) - strtotime('-1 year');
                if($authAtExpired > AmazonAccountAds::AUTH_AT_EXPIRED){
                    return response()->json(['status' => false, 'message' => '已授权！']);
                }
            }
            if (!in_array($model->amazon_account->aws_region, ['NA','EU','FE'])) {
                return response()->json(['status' => false, 'message' => '广告授权区域异常！']);
            }
            $regionUrl = AmazonAccountAds::$_authUrl[$model->amazon_account->aws_region];
            $authorize = new Authorize();
            $oauthUrl = $authorize->getOauthUrl($regionUrl,$id);
            return response()->json(['status' => true, 'message' => '操作成功！', 'oauth_url' => $oauthUrl]);
        }catch (\Exception $e){
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
